package cn.stylefeng.guns.modular.pay.controller;

import cn.stylefeng.guns.config.pay.SignConfig;
import cn.stylefeng.guns.modular.account.model.result.AccountResult;
import cn.stylefeng.guns.modular.account.service.AccountService;
import cn.stylefeng.guns.modular.pay.exception.AuthorizationException;
import cn.stylefeng.guns.modular.pay.model.Charge;
import cn.stylefeng.guns.modular.pay.model.ChargeParam;
import cn.stylefeng.guns.modular.pay.utils.QRCodeGenerator;
import cn.stylefeng.guns.modular.recharge.model.params.RechargeParam;
import cn.stylefeng.guns.modular.recharge.service.RechargeService;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.roses.core.util.HttpContext;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.WriterException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * @Description: PayController
 * @Author liuqiang
 * @Date 2020-02-08 14:20
 */
@RestController
@RequestMapping("/pay")
@Slf4j
public class PayController{

    @Autowired
    private RechargeService rechargeService;

    @Autowired
    private AccountService accountService;

    @GetMapping("/recharge")
    public ResponseData pay(ChargeParam chargeParam){
        String channel = chargeParam.getChannel();
        if(!"alipay_csb".equals(channel) && !"wechat_csb".equals(channel)){
            throw new ServiceException(BizExceptionEnum.PARAM_WRONG.getCode(),"该充值渠道暂不支持！");
        }

        String phone = chargeParam.getPhone();
        if(StringUtils.isBlank(phone)){
            throw new ServiceException(BizExceptionEnum.PARAM_MISSING.getCode(),"手机号不能为空！");
        }

        AccountResult account = accountService.getByPhone(phone);
        if(account == null){
            throw new ServiceException(BizExceptionEnum.PARAM_WRONG.getCode(),"该账号不存在！");
        }

        HttpServletRequest request = HttpContext.getRequest();
        String orderId = UUID.randomUUID().toString();
        Map<String, Object> chargeMap = new HashMap<String, Object>();
        chargeMap.put("amount", chargeParam.getAmount());
        chargeMap.put("subject", "账户充值");
        chargeMap.put("body", String.format("充值:%s元",chargeParam.getAmount()));
        chargeMap.put("order_no", orderId);
        chargeMap.put("channel", channel);
        chargeMap.put("client_ip", request.getRemoteAddr());
        chargeMap.put("app", SignConfig.APP_ID);
        chargeMap.put("currency","CNY");
        try {
            Charge charge = Charge.create(chargeMap);
            log.info("聚合支付返回=={}", JSONObject.toJSONString(charge));
            if (charge.getReqSuccessFlag()){
                RechargeParam rechargeParam = new RechargeParam();
                rechargeParam.setPhone(chargeParam.getPhone());
                rechargeParam.setAmount(chargeParam.getAmount());
                rechargeParam.setChannel(channel);
                rechargeParam.setSerialNo(charge.getId());
                rechargeParam.setOrderNo(orderId);
                rechargeParam.setPhone(chargeParam.getPhone());

                rechargeService.add(rechargeParam);

                Map<String,String> csb;
                if(channel.equals("alipay_csb")){
                    csb = (Map<String,String>)charge.getCredential().get("alipay_csb");
                }else {
                    csb = (Map<String,String>)charge.getCredential().get("wechat_csb");
                }

                String qrCode = csb.get("qr_code");
                Map<String,String> map = new HashMap<>();
                map.put("qr_code",qrCode);
                map.put("orderId",orderId);
                return ResponseData.success(map);
            }else {
                throw new ServiceException(BizExceptionEnum.PAY_ERROR.getCode(),charge.getFailureMsg());
            }

        } catch (AuthorizationException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @GetMapping("/test")
    public ResponseEntity<byte[]> test(){
        HttpHeaders headers = new HttpHeaders();
        headers.add("content-type", "image/jpeg");
        Map<String, Object> chargeMap = new HashMap<String, Object>();
        chargeMap.put("amount", 100);
        chargeMap.put("subject", "测试支付");
        chargeMap.put("body", "测试body");
        chargeMap.put("order_no", UUID.randomUUID());
        chargeMap.put("channel", "alipay_csb");
        chargeMap.put("client_ip", "120.244.56.41");
        chargeMap.put("app", "app_P9cHyCpnY063jTk7");
        chargeMap.put("currency","CNY");
        chargeMap.put("description","我是中文");
        try {
            Charge charge = Charge.create(chargeMap);
            Map<String,String> wechat_csb = (Map<String,String>)charge.getCredential().get("alipay_csb");
            String text = wechat_csb.get("qr_code");
            byte[] codeImage = QRCodeGenerator.getQRCodeImage(text, 260, 260);
            return new ResponseEntity<>(codeImage,headers, HttpStatus.OK);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Map<String, Object> chargeMap = new HashMap<String, Object>();
        chargeMap.put("amount", 0.01);
        chargeMap.put("subject", "测试支付");
        chargeMap.put("body", "测试body");
        chargeMap.put("order_no", UUID.randomUUID());
        chargeMap.put("channel", "wechat_csb");
        chargeMap.put("client_ip", "120.244.56.41");
        chargeMap.put("app", "app_P9cHyCpnY063jTk7");
        chargeMap.put("currency","CNY");
        chargeMap.put("description","我是中文");
//        Map<String,Object> extraMap = new HashMap<>();
//        extraMap.put("user_id","123");
//        extraMap.put("return_url","http://47.94.8.13/service/callback");
//        chargeMap.put("extra",extraMap);
        Charge charge;
        try {
            charge = Charge.create(chargeMap);
            printResult(charge);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void printResult(Charge charge) {
        if (charge.getReqSuccessFlag()){//http请求成功
            System.out.println(JSON.toJSONString(charge));
        }else {//http请求失败
            System.out.println(JSON.toJSONString(charge));
            String failureCode = charge.getFailureCode();
            String failureMsg = charge.getFailureMsg();
            System.out.println("failureCode:"+failureCode);
            System.out.println("failureMsg:"+failureMsg);
        }
    }
}
